const db = require("../model/mysql/db");
const util = require("../common/util");

async function register(req,res,next){
    const requiredFields = ['username', 'password'];
    const missing = requiredFields.filter(field => !req.body[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    }
    let params = [
        req.body.username,
        util.md5Pwd(req.body.password),
        "http://localhost:3527/images/avatar/avatar-default4.png",
        "保密"
    ] 
    const sql = "INSERT INTO users (username,password,avatar,sex) VALUES(?,?,?,?);"
    try {
        let result =await db.query(sql,params);
        util.FormatJSONData(201,"注册成功");
        res.status(201).json(util.FormatJSONData(201,"注册成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
};

async function login(req,res){
    const requiredFields = ['username', 'password'];
    const missing = requiredFields.filter(field => !req.body[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    }
    let params = [
        req.body.username,
        util.md5Pwd(req.body.password),
    ];
    const sql = "SELECT * FROM users WHERE username = ? AND password = ?"
    try{
        let result = await db.query(sql,params);
        delete result[0].password;
        res.status(200).json(util.FormatJSONData(200,"登录成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
};

async function findbyid(req,res){
    const requiredFields = ['user_id'];
    const missing = requiredFields.filter(field => !req.params[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    }
    let params = [
        req.params.user_id
    ];
    const sql = "SELECT * FROM users WHERE user_id = ?"
    try{
        let result = await db.query(sql,params);
        delete result[0].password;
        res.status(200).json(util.FormatJSONData(200,"查询成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
};

async function find(req,res) {
    const requiredFields = ['username'];
    const missing = requiredFields.filter(field => !req.params[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    }
    let params = [
        req.params.username
    ];
    const sql = "SELECT * FROM users WHERE username = ?"
    try{
        let result = await db.query(sql,params);
        delete result[0].password;
        res.status(200).json(util.FormatJSONData(200,"查询成功",result));
    } catch{
        util.err(500,"错误！！！");
        res.status(500).json(util.FormatJSONData(500,"服务器错误"));
    }
}

//
async function update(req, res) {
    const requiredFields = ['user_id'];
    const missing = requiredFields.filter(field => !req.body[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    }

    // 查询用户是否存在
    let params = [req.body.user_id];
    let sql = "SELECT * FROM users WHERE user_id = ?";
    let qres;

    try {
        qres = await db.query(sql, params);
        if (!qres || qres.length === 0) {
            return res.status(404).json(util.FormatJSONData(404, '用户不存在'));
        }
    } catch (err) {
        console.error('数据库错误:', err);
        return res.status(500).json(util.FormatJSONData(500, "服务器错误"));
    }

    try {
        // 收集并校验更新字段
        const nickname = req.body.nickname || null;
        const student_id = req.body.student_id || null;
        const grade = req.body.grade || null;
        const category = req.body.category || null;
        const major = req.body.major || null;
        const sex = req.body.sex || null;

        if (!nickname && !student_id && !grade && !category && !major && !sex) {
            return res.status(400).json(util.FormatJSONData(400, '至少需要更新一个字段'));
        }

        const updateParams = [nickname, student_id, grade, category, major, sex, req.body.user_id];
        const updateSql = `
            UPDATE users 
            SET
                nickname = ?, 
                student_id = ?,
                grade = ?,
                category = ?,
                major = ?,
                sex = ?
            WHERE user_id = ?
        `;

        const result = await db.query(updateSql, updateParams);
        return res.status(200).json(util.FormatJSONData(200, "修改成功", result));
    } catch (err) {
        console.error('数据库错误:', err);
        return res.status(500).json(util.FormatJSONData(500, "服务器错误"));
    }
}

async function avatar(req, res) {
    const requiredFields = ['user_id'];
    const missing = requiredFields.filter(field => !req.body[field]);
    if (missing.length > 0) {
        return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
    }

    // 查询用户是否存在
    let params = [req.body.user_id];
    let sql = "SELECT * FROM users WHERE user_id = ?";
    let qres;

    try {
        qres = await db.query(sql, params);
        if (!qres || qres.length === 0) {
            return res.status(404).json(util.FormatJSONData(404, '用户不存在'));
        }
    } catch (err) {
        console.error('数据库错误:', err);
        return res.status(500).json(util.FormatJSONData(500, "服务器错误"));
    }

    try {
        const updateParams = [req.body.avatar,req.body.user_id];
        const updateSql = `UPDATE users SET avatar = ? WHERE user_id = ?`;
        const result = await db.query(updateSql, updateParams);
        return res.status(200).json(util.FormatJSONData(200, "修改成功", result));
    } catch (err) {
        console.error('数据库错误:', err);
        return res.status(500).json(util.FormatJSONData(500, "服务器错误"));
    }
}

module.exports = {
    register,
    login,
    findbyid,
    update,
    avatar,
    find
}
// async function update(req, res, next) {
//     const requiredFields = ['user_id'];
//     const missing = requiredFields.filter(field => !req.body[field]);
//     if (missing.length > 0) {
//         return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
//     }

//     try {
//         // 查询用户是否存在
//         const qres = await findbyid(req, res);
//         if (!qres || qres.length === 0) {
//             return res.status(404).json(util.FormatJSONData(404, '用户不存在'));
//         }

//         // 收集并校验更新字段
//         const username = req.body.username || null;
//         const password = req.body.password ? util.md5Pwd(req.body.password) : null;
//         const nickname = req.body.nickname || null;
//         const student_id = req.body.student_id || null;

//         const params = [username, password, nickname, student_id, req.body.user_id];

//         const sql = `
//             UPDATE users 
//             SET 
//                 username = ?, 
//                 password = ?, 
//                 nickname = ?, 
//                 student_id = ? 
//             WHERE user_id = ?
//         `;

//         const result = await db.query(sql, params);
//         res.status(201).json(util.FormatJSONData(201, "修改成功", result));
//     } catch (err) {
//         console.error('数据库错误:', err); // 记录错误便于排查
//         util.err(500, "服务器错误");
//         res.status(500).json(util.FormatJSONData(500, "服务器错误"));
//     }
// }async function update(req, res, next) {
//     const requiredFields = ['user_id'];
//     const missing = requiredFields.filter(field => !req.body[field]);
//     if (missing.length > 0) {
//         return res.status(400).json(util.FormatJSONData(400, `缺少必填字段: ${missing.join(', ')}`));
//     }

//     try {
//         // 查询用户是否存在
//         const qres = await findbyid(req, res);
//         if (!qres || qres.length === 0) {
//             return res.status(404).json(util.FormatJSONData(404, '用户不存在'));
//         }

//         // 收集并校验更新字段
//         const username = req.body.username || null;
//         const password = req.body.password ? util.md5Pwd(req.body.password) : null;
//         const nickname = req.body.nickname || null;
//         const student_id = req.body.student_id || null;

//         const params = [username, password, nickname, student_id, req.body.user_id];

//         const sql = `
//             UPDATE users 
//             SET 
//                 username = ?, 
//                 password = ?, 
//                 nickname = ?, 
//                 student_id = ? 
//             WHERE user_id = ?
//         `;

//         const result = await db.query(sql, params);
//         res.status(201).json(util.FormatJSONData(201, "修改成功", result));
//     } catch (err) {
//         console.error('数据库错误:', err); // 记录错误便于排查
//         util.err(500, "服务器错误");
//         res.status(500).json(util.FormatJSONData(500, "服务器错误"));
//     }
// }